package com.tech.view.component.input;

import com.tech.view.common.ColorUtil;
import com.tech.view.common.FontUtil;
import com.tech.view.common.SwingTestUtils;
import com.tech.view.panel.HOTPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;

/**
 * 搜索框
 */
public class SearchField extends JTextField {
	private String tipText;
	private Font font = FontUtil.SMALL_FONT.deriveFont(20f);

	public SearchField() {
		this(null);
	}

	public SearchField(String tipText) {
		this.tipText = tipText;

		initService();
		initComponents();
		setListeners();
		initView();
	}

	public static void main(String[] args) {
		SwingTestUtils.loadSkin();
		SearchField field = new SearchField("请输入关键词");
		field.setPreferredSize(new Dimension(400, 40));
		SwingTestUtils.test(field);
	}

	private void initService() {

	}

	private void initComponents() {

	}

	private void initView() {
		// 让绘制的背景色显示出来
		setOpaque(false);
		setFont(font);
		setForeground(ColorUtil.FONT_COLOR);
	}

	private void setListeners() {
	}

	@Override
	protected void paintComponent(Graphics g) {
		// 在这里绘制自定义背景，父类方法不会覆盖这个背景，因为已经调用了setOpaque(false)

		super.paintComponent(g);
		if (tipText != null && "".equals(getText())) {
			Graphics2D g2 = (Graphics2D) g.create();
			g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			FontRenderContext frc = FontUtil.FRC;
			g2.setFont(font);
			g2.setColor(ColorUtil.SHALLOW_FONT_COLOR);
			Rectangle2D stringBounds = font.getStringBounds(tipText, frc);
			g2.drawString(tipText, getMargin().left, (getPreferredSize().height + (int) stringBounds.getHeight()) / 2 - 5);
			g2.dispose();
		}
	}

	// 绘制圆角边框，原理是绘制实心的椭圆
	@Override
	protected void paintBorder(Graphics g) {
		int h = getHeight();
		int w = getWidth();
		Graphics2D g2 = (Graphics2D) g.create();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.drawRoundRect(1, 1, w - 2, h - 2, h, h);
		g2.dispose();
		super.paintBorder(g2);
	}
}
